package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
public class AutoFillAspect {

    @Pointcut("execution(* com.sky.mapper.*.*(..))&&@annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointcut() {
    }

    @Before("autoFillPointcut()")
    public void autoFill(JoinPoint joinPoint) {
        //1.获取方法签名
        MethodSignature sign = (MethodSignature) joinPoint.getSignature();
        Method method = sign.getMethod();
        //2.获取注解类型
        AutoFill annotation = method.getAnnotation(AutoFill.class);
        OperationType type = annotation.value();
        //3.获取参数
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object arg = args[0];
        //4.为参数赋值
        Long id = BaseContext.getCurrentId();
        Class<?> c = arg.getClass();
        try {
            Method setUpdateTime = c.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setUpdateUser = c.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            if (type == OperationType.INSERT) {
                Method setCreateTime = c.getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setCreateUser = c.getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                setCreateUser.invoke(arg, id);
                setUpdateUser.invoke(arg, id);
                setCreateTime.invoke(arg, LocalDateTime.now());
                setUpdateTime.invoke(arg, LocalDateTime.now());
            } else if (type == OperationType.UPDATE) {
                setUpdateUser.invoke(arg, id);
                setUpdateTime.invoke(arg, LocalDateTime.now());
            }
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}
